#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <cstring>
#include <thread>

#include "InetAddr.hpp"

int sockfd = -1;
std::string serverip;
uint16_t serverport;

//用户端一般会内置服务端的ip和port，所以我们需要传入服务端ip和port两项
void Usage(std::string proc)
{
    std::cerr << "Usage: " << proc << " serverip serverport" << std::endl;
}

void InitClient(const std::string &serverip, uint16_t serverport)
{
    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(sockfd < 0)
    {
        std::cout << "create socket errror" << std::endl;
        return;
    }
}

void recver()
{
    while (true)
    {
        struct sockaddr_in temp;
        memset(&temp, 0, sizeof(temp));
        char buffer[1024];
        socklen_t templen = sizeof(temp);
        ssize_t n = recvfrom(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr*)&temp, &templen);
        if(n > 0)
        {
            buffer[n] = 0;
            std::cerr << buffer << std::endl;
        }
    }
}

void sender()
{
    InetAddr server(serverport,serverip);
    while(true)
    {
        std::cout << "Please Enter@ ";
        std::string line;
        getline(std::cin, line);
        socklen_t serverlen = sizeof(server);
        sendto(sockfd, line.c_str(), line.size(), 0, (struct sockaddr *)&server, serverlen);
    }
}

int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }
    serverip = argv[1];
    serverport = std::stoi(argv[2]);
    InitClient(serverip, serverport);

    std::thread tsend(sender);
    std::thread trecv(recver);

    tsend.join();
    trecv.join();
    return 0;
}
